<template>
  <el-dialog
    :title="exam_id ? '编辑考试' : '新增考试'"
    :close-on-click-modal="false"
    :visible.sync="visible"
    width="950px"
  >
    <el-form
      :model="examForm"
      :rules="examFormRules"
      ref="examForm"
      label-width="80px"
    >
      <el-row :gutter="5">
        <el-col :span="12">
          <el-form-item label="考试名称" prop="examName">
            <el-input
              v-model="examForm.examName"
              placeholder="请输入考试名称"
              clearable
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="考试类型" prop="examType">
            <nice-select
              v-model="examForm.examType"
              placeholder="请选择考试类型"
              clearable
              :options="selectEnums.nice_exam.exam_type"
            ></nice-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="5">
        <el-col :span="12">
          <el-form-item label="考试开始" prop="examTime">
            <el-date-picker
              v-model="examForm.examTime"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="请选择考试起始时间"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="考试截止" prop="endTime">
            <el-date-picker
              v-model="examForm.endTime"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="请选择考试截止时间"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-form-item label="" prop="isUnify">
          <el-checkbox v-model="examForm.isUnify">统一时间考试</el-checkbox>
        </el-form-item>
      </el-row>
      <el-row
        v-for="(item, index) in examForm.examCourseList"
        :gutter="5"
        :key="index"
      >
        <el-col :span="12">
          <el-form-item
            :label="getLabel(index)"
            prop="name"
            :prop="'examCourseList.' + index + '.courseId'"
          >
            <el-select
              v-model="item.courseId"
              filterable
              remote
              reserve-keyword
              placeholder="请选择课程"
              :remote-method="remoteCourseMethod"
              :loading="loading"
              clearable
              @change="changeCourse($event, index)"
              :disabled="index != examForm.examCourseList.length - 1"
              multiple
            >
              <el-option
                v-for="item in courseList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="大于" prop="gtScore">
            <el-input
              v-model="item.gtScore"
              placeholder=""
              clearable
              :disabled="index != examForm.examCourseList.length - 1"
              type="number"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="小于等于" prop="leScore">
            <el-input
              v-model="item.leScore"
              placeholder=""
              clearable
              :disabled="index != examForm.examCourseList.length - 1"
              type="number"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="1" class="margin-top10 margin-left10">
          <i
            class="el-icon-delete"
            @click="deleteGood(item, index)"
            v-if="index != examForm.examCourseList.length - 1"
          ></i>
          <el-button type="text" @click="addGood(item)" size="small" v-else
            >确定</el-button
          >
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="考试说明" prop="description">
            <el-input
              v-model="examForm.description"
              placeholder="请输入考试说明"
              clearable
              type="textarea"
              :rows="3"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false" size="small">取消</el-button>
      <el-button
        type="primary"
        @click="dataFormSubmit"
        size="small"
        v-preventReClick
        >确定</el-button
      >
    </span>
  </el-dialog>
</template>
<script>
import { myEnumsMixins } from '@/utils/mixins'
import {
  addEaxm,
  updateExam,
  getExamDetailsById,
  queryCourseList
} from '@/api/exam.js'
import { getAllCourse } from '@/api/user.js'
export default {
  data () {
    return {
      visible: false,
      loading: false,
      courseList: [],
      exam_id: '',
      examForm: {
        examType: '',
        examName: '',
        examTime: '',
        endTime: '',
        isUnify: false,
        description: '',
        examCourseList: [{ courseId: '', leScore: '', gtScore: '', id: '' }]
      },
      // pickerOptions: {
      //   disabledDate (time) {
      //     return time.getTime() > Date.now()
      //   }
      // },
      examFormRules: {
        examName: [
          { required: true, message: '考试名称不能为空', trigger: 'blur' }
        ],
        examType: [
          { required: true, message: '考试类型不能为空', trigger: 'blur' }
        ],
        examTime: [
          { required: true, message: '考试开始时间不能为空', trigger: 'blur' }
        ],
        endTime: [
          { required: true, message: '考试截止时间不能为空', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '考试说明不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  props: {
    mode: {
      type: String,
      default: ''
    }
  },
  mixins: [myEnumsMixins],
  methods: {
    init (id) {
      this.visible = true
      this.exam_id = id
      this.$nextTick(() => {
        this.$refs['examForm'].resetFields()
        this.examForm.examCourseList = []
      })
      if (this.exam_id) {
        this.queryCourseList()
      } else {
        this.examForm.examCourseList = [
          { courseId: '', leScore: '', gtScore: '', id: '' }
        ]
      }
    },
    async getExamDetailsById () {
      let res = await getExamDetailsById({ id: this.exam_id })
      if (res[0]) {
        return
      }
      if (res[1].code == 0) {
        let response = res[1].data
        this.examForm = {
          examType: response.niceExam.examType,
          examName: response.niceExam.examName,
          examTime: response.niceExam.examTime,
          endTime: response.niceExam.endTime,
          isUnify: !!response.niceExam.isUnify,
          description: response.niceExam.description
        }
        if (response.examCourseList && response.examCourseList.length) {
          let arr = response.examCourseList.filter(item => {
            return item.type == 2
          })
          arr.forEach((ele, index) => {
            if (index == 0) {
              this.examForm.examCourseList.push({
                courseId: [ele.courseId],
                leScore: ele.leScore,
                gtScore: ele.gtScore,
                id: this.exam_id
              })
            } else {
              this.examForm.examCourseList.forEach(ele => {})
            }
          })
          // this.examForm.examCourseList =arr.map(ele=>{
          //   return {
          //     courseId:[ele.courseId],
          //     leScore:ele.leScore,
          //     gtScore:ele.gtScore,
          //     id:this.exam_id
          //   }
          // })
          this.examForm.examCourseList.push({
            courseId: '',
            leScore: '',
            gtScore: '',
            id: ''
          })
        }
      }
    },
    async queryCourseList () {
      let res = await queryCourseList({ examId: this.exam_id })
      if (res[0]) {
        return
      }
      if (res[1].code == 0) {
        this.courseList = res[1].data.list.map(ele => {
          return {
            label: ele.name,
            value: ele.id
          }
        })
        this.getExamDetailsById()
      }
    },
    dataFormSubmit () {
      this.$refs['examForm'].validate(async valid => {
        if (valid) {
          if (this.examForm.examCourseList.length == 1) {
            this.$message.warning('请选择课程！')
            return false
          }
          let examCourseList = []
          let data =
            this.examForm.examCourseList.length > 3
              ? this.examForm.examCourseList.slice(0, 3)
              : this.examForm.examCourseList.slice(0, 2)
          data.forEach(ele => {
            ele.courseId.forEach(item => {
              examCourseList.push({
                courseId: item,
                leScore: ele.leScore,
                gtScore: ele.gtScore,
                id: this.exam_id
              })
            })
          })
          examCourseList.forEach(ele => {
            if (!this.exam_id) {
              delete ele.id
            }
          })
          let params = {
            niceExam: {
              examType: this.examForm.examType,
              examName: this.examForm.examName,
              examTime: this.examForm.examTime,
              endTime: this.examForm.endTime,
              isUnify: this.examForm.isUnify ? 1 : 0,
              description: this.examForm.description
            },
            examCourseList: examCourseList
          }
          let res = this.exam_id
            ? await updateExam(params)
            : await addEaxm(params)
          if (res[0]) {
            return
          }
          if (res[1].code == 0) {
            this.$message.success(
              this.exam_id ? '编辑考试成功！' : '新增考试成功！'
            )
            this.visible = false
            this.$emit('refreshData')
          }
        }
      })
    },
    changeCourse (e, index) {},
    async remoteCourseMethod (query) {
      if (query !== '') {
        this.loading = true
        let res = await getAllCourse({ 'nice_course.name': query })
        if (res[0]) {
          return
        }
        let data = res[1]
        this.loading = false
        if (data && data.code === 0) {
          if (data.data.pageList.list && data.data.pageList.list.length) {
            this.courseList = data.data.pageList.list.map(item => {
              return {
                label: item.name,
                value: item.id
              }
            })
          } else {
            this.courseList = []
          }
        }
      }
    },
    getLabel (index) {
      let indx = index + 1
      return '课程' + indx
    },
    deleteGood (item, index) {
      console.log(3333333333, index, this.examForm.examCourseList)
      this.examForm.examCourseList.splice(index, 1)
      console.log(32222222, this.examForm.examCourseList)
    },
    addGood (item) {
      if (!item.courseId.length) {
        this.$message.warning('请选择课程！')
        return false
      }
      if (!item.leScore || !item.gtScore) {
        this.$message.warning('请输入分数区间！')
        return false
      }
      if (this.examForm.examCourseList.length == 4) {
        this.$message.warning('课程最多只能选择3个！')
        return false
      }
      this.examForm.examCourseList.push({
        courseId: '',
        leScore: '',
        gtScore: '',
        id: this.exam_id
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.el-date-editor {
  width: 100% !important;
}
</style>
